import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/dialog/custom_bottom_sheet.dart';
import 'package:enterprise_v6_app/app/components/dialog/exit_tips.dart';
import 'package:enterprise_v6_app/app/components/regional_organization_tree/regional_organization_tree_view.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/customEndDrawer.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/entities/common/risk_tree_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/double_control/double_control_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/double_prevention_page/risk_control_page/risk_control_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

///安全风险辨识
class RiskSecurityIdentificationController extends GetxController {
  /// 筛选右侧栏控制Key
  final riskRightScaffoldKey = GlobalKey<ScaffoldState>();

  ///当前页面等级  level :1 全部 2 对象 3 单元 4 事件 5
  ///措施 需要筛选赋值判断当前啥类型 目前默认‘’对象’‘
  int currentPageLevel = 2;

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 筛选后的标题
  String? title = '全部';

  /// 选中的节点
  RiskTreeEntity selectedEntity = RiskTreeEntity();

  /// 筛选按钮
  void onFilterButtonPressed() {
    final RiskControlController controller = Get.find<RiskControlController>();
    controller.filterWidget.value = _filterWidget();
    controller.riskRightScaffoldKey.currentState?.openEndDrawer();
    // riskRightScaffoldKey.currentState?.openEndDrawer();
  }

  /// 获取安全风险辨识列表数据
  Future<List<DoubleControlChildren>> getRiskSecurityIdentificationList(
    int pageIndex,
    int pageSize, {
    String? search, //搜索关键字
  }) async {
    final List<RiskTreeEntity> data = [];
    data.add(selectedEntity);
    final res = await HttpUtil()
        .generatePostRequest<List<DoubleControlChildren>>(
          Interface.getRiskList,
          data: data,
        )
        .execute();
    List<DoubleControlChildren> list = [];
    res.onSuccess((result) {
      AppLogger.log(result.data.toString());
      list = result.data!;
    });

    return list;
  }

  ///点击+新增or编辑界面 对象
  void onClickAddObj({DoubleControlChildren? item}) {
    Get.toNamed(AppRoutes.riskOnClickAddObjPage, arguments: item?.id);
  }

  ///点击+新增or编辑界面 单元
  void onClickAddUnit({DoubleControlChildren? item}) {
    Get.toNamed(AppRoutes.riskOnClickAddUnitPage, arguments: {'editId': item?.id, 'riskObjectId': selectedEntity});
  }

  ///点击+新增or编辑界面 事件
  void onClickAddEvent({DoubleControlChildren? item}) {
    Get.toNamed(AppRoutes.riskOnClickAddEventPage, arguments: {'editId': item?.id, 'riskUnitId': selectedEntity});
  }

  ///点击+新增or编辑界面 措施
  void onClickAddStep({DoubleControlChildren? item}) {
    Get.toNamed(AppRoutes.riskOnClickAddStepPage, arguments: {'editId': item?.id, 'riskStepId': selectedEntity});
  }

  ///安全风险辨识详情 对象
  ///currency//TbBaseRiskObject/getRiskObjectById 参数id 4541a8e2-8b09-4bd0-8700-854b27b01d4d
  void onRiskButtonObjPressed(String? id) {
    Get.toNamed(AppRoutes.riskObjDetails, arguments: id);
  }

  ///安全风险辨识详情 单元
  ///currency//TbBaseRiskUnit/getTbBaseRiskUnitById 参数id 4541a8e2-8b09-4bd0-8700-854b27b01d4d
  void onRiskButtonUnitPressed(String? id) {
    Get.toNamed(AppRoutes.riskUnitDetails, arguments: id);
  }

  ///安全风险辨识详情 事件
  ///currency//tbBaseRiskEvents/getTbBaseRiskEventsById 参数id 4541a8e2-8b09-4bd0-8700-854b27b01d4d
  void onRiskButtonEventPressed(String? id) {
    Get.toNamed(AppRoutes.riskEventDetails, arguments: id);
  }

  ///安全风险辨识详情 措施
  ///currency//tbBaseControlMeasure/getBaseControlMeasureById 参数id 4541a8e2-8b09-4bd0-8700-854b27b01d4d
  void onRiskButtonStepPressed(String? id) {
    Get.toNamed(AppRoutes.riskStepDetails, arguments: id);
  }

  /// 选择更多
  void selectQualityAndLevel(DoubleControlChildren item) {
    CustomBottomSheet<String>(
      dataList: const ['编辑', '删除'],
      onConfirm: (value) {
        if (value == '删除') {
          Get.dialog<bool>(ExitTips(
            content: _selectLevel(item.level),
            func: (v) {
              if (v) {
                _delRiskById(item.level, item.id);
              }
            },
          ));
        } else if (value == '编辑') {
          //有数据带入
          if (currentPageLevel == 1) {
            //全部
          } else if (currentPageLevel == 2) {
            //对象
            onClickAddObj(item: item);
          } else if (currentPageLevel == 3) {
            //单元
            onClickAddUnit(item: item);
          } else if (currentPageLevel == 4) {
            //事件
            onClickAddEvent(item: item);
          } else if (currentPageLevel == 5) {
            //管控措施
            onClickAddStep(item: item);
          }
        }
        update();
      },
    ).showBottomSheetDialog();
  }

  String _selectLevel(int? currentPageLevel) {
    if (currentPageLevel == 1) {
      //全部
      return '确定删除该全部？';
    } else if (currentPageLevel == 2) {
      //对象
      return '确定删除该对象？';
    } else if (currentPageLevel == 3) {
      //单元
      return '确定删除该单元？';
    } else if (currentPageLevel == 4) {
      //事件
      return '确定删除该事件？';
    } else if (currentPageLevel == 5) {
      //管控措施
      return '确定删除该措施？';
    }
    return '确定删除该对象？';
  }

  ///删除风险分析
  void _delRiskById(int? level, String? id) {
    if (level == 1) {
      //全部
    } else if (level == 2) {
      //对象 /currency//TbBaseRiskObject/delRiskObjectById
      delRiskObjectById(id, Interface.delRiskObjectById);
    } else if (level == 3) {
      //单元
      delRiskObjectById(id, Interface.delTbBaseRiskUnit);
    } else if (level == 4) {
      //事件
      delRiskObjectById(id, Interface.delTbBaseRiskEventsById);
    } else if (level == 5) {
      //管控措施
      delRiskObjectById(id, Interface.delBaseControlMeasure);
    }
  }

  delRiskObjectById(String? id, String url) async {
    final res = await HttpUtil().generatePostRequest(
      url,
      data: [id],
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        AppToast.show('删除成功');
      }
    });
    res.onError((result) {
      AppToast.showError('删除失败');
    });
    globalKey.currentState?.onRefresh();
  }

  /// 重置
  void reset() {
    final RiskControlController controller = Get.find<RiskControlController>();
    controller.riskRightScaffoldKey.currentState?.closeEndDrawer();
    selectedEntity = RiskTreeEntity();
    globalKey.currentState!.onRefresh();
    title = '全部';
    update();
  }

  /// 确定
  void confirm() {
    Get.back();
    //修改当前安全风险等级level
    currentPageLevel = selectedEntity.level! + 1;
    if (selectedEntity.level == 1) {
      title = '全部';
    } else if (selectedEntity.level == 2) {
      title = '全部/${selectedEntity.name}';
    } else {
      title = '${selectedEntity.path}/${selectedEntity.name}';
      if (title != null && title!.startsWith('/')) {
        title = title?.substring(1, title?.length);
        title = '全部/$title';
      }
    }
    globalKey.currentState!.onRefresh();
    update();
  }

  ///初始风险等级：1_重大 2_较大 3_一般 4_低
  String backRiskLevelName(String? riskDegree) {
    if (riskDegree == '1') {
      return '重大风险';
    } else if (riskDegree == '2') {
      return '较大风险';
    } else if (riskDegree == '3') {
      return '一般风险';
    } else if (riskDegree == '4') {
      return '低风险';
    }
    return '';
  }

  Widget _filterWidget() {
    return CustomEndDrawer(
      centerContext: Column(
        children: [
          RegionalOrganizationTreePage(
            selectedEntity: selectedEntity,
            onCallBack: (RiskTreeEntity entity) {
              selectedEntity = entity;
            },
          ),
        ],
      ),
      reset: reset,
      confirm: confirm,
    );
  }
}
